package org.jeecg.modules.demo.util;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.allinpay.sdk.OpenClient;
import com.allinpay.sdk.bean.BizParameter;
import com.allinpay.sdk.bean.OpenConfig;
import com.allinpay.sdk.bean.OpenResponse;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.Base64Utils;
import org.jeecg.modules.demo.entity.SmtCompanyInfo;
import org.jeecg.modules.demo.weixin.dto.PayDto;
import org.jeecg.modules.demo.weixin.util.FileUtils;
import org.jeecg.modules.demo.weixin.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
public class Allinpay {


    /**
     * 通商云       创建会员
     */

    private static OpenClient client;


    public static void configClient() {
        final String url = "http://test.allinpay.com/open/gateway";
        final String appId = "1283233906081939458";
        final String secretKey = "eMDVxpfvt1k8mIiCZvDLWx9wtJcdtVBQ";
        final String privateKeyPath = "/E:/openspace/1283233906081939458.pfx";
        final String pwd = "939458";
        final String tlPublicKey = "/E:/openspace/TLCert-test.cer";
        final OpenConfig oc = new OpenConfig(url, appId, secretKey, privateKeyPath, pwd, tlPublicKey);
        try {
            client = new OpenClient(oc);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建会员
     *
     * @return
     */
    public static JSONObject createMember(String bizUserId, Long type) {
        configClient();
        BizParameter param = new BizParameter();
        param.put("bizUserId", bizUserId);
        param.put("memberType", type);
        param.put("source", 2L);
        try {
            OpenResponse execute = client.execute("allinpay.yunst.memberService.createMember", param);

            if (execute.getCode().equals("10000") && "OK".equals(execute.getSubCode())) {
                return JSONObject.parseObject(execute.getData());
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送验证码
     *
     * @return
     */

    public static JSONObject sendVerificationCode(String bizUser, String phone) {
        configClient();
        BizParameter param = new BizParameter();
        param.put("bizUserId", bizUser);
        param.put("phone", phone);
        param.put("verificationCodeType", 9L);
        try {
            OpenResponse execute = client.execute("allinpay.yunst.memberService.sendVerificationCode", param);
            if (execute.getCode().equals("10000") && "OK".equals(execute.getSubCode())) {
                return JSONObject.parseObject(execute.getData());
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 绑定手机号码
     *
     * @return
     */
    public static JSONObject bindPhone(String bizUser, String phone, String verificationCode) {
        configClient();
        BizParameter param = new BizParameter();
        param.put("bizUserId", "test000022");
        param.put("phone", "13712312311");
        param.put("verificationCode", "11111");
        try {
            final OpenResponse response = client.execute("allinpay.yunst.memberService.bindPhone", param);
            if (response.getCode().equals("10000") && "OK".equals(response.getSubCode())) {
                return JSONObject.parseObject(response.getData());
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 申请退款  （分账退款不走该接口）
     *
     * @return
     */
    public static JSONObject refund(String oriBizOrderNo, String oriOrderNo, BigDecimal amount) {
        configClient();
        BizParameter param = new BizParameter();
        param.put("bizOrderNo", System.currentTimeMillis() + RandomUtil.randomNumbers(3) + "tk");
        param.put("oriBizOrderNo", oriBizOrderNo);
        param.put("oriOrderNo", oriOrderNo);
        param.put("bizUserId", "yc0001");
        param.put("amount", amount.multiply(BigDecimal.valueOf(100)).longValue());
        param.put("refundType", "D0");

        try {
            final OpenResponse response = client.execute("allinpay.yunst.orderService.refund", param);
//            System.out.println(response.getCode());
            if (response.getCode().equals("10000") && "OK".equals(response.getSubCode())) {
                return JSONObject.parseObject(response.getData());
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 分账退款
     *
     * @return
     */
    public static OpenResponse refundSplit() {
        configClient();
        BizParameter param = new BizParameter();
        param.put("bizOrderNo", "98211254856225254458526810");
        param.put("oriBizOrderNo", "78952233651232257127");
        param.put("bizUserId", "yc0001");
        param.put("amount", 10);
        param.put("refundType", "D0");
        param.put("backUrl", "http://ceshi.allinpay.com");

        //订单退款详情
        JSONArray orderRefundList = new JSONArray();
        JSONObject object = new JSONObject();
        object.put("splitBizOrderNo", "78952233651232257127");
        object.put("amount", 10);
        object.put("bizUserId", "test0001");
        //分账退款总金额
        object.put("totalSplitAmount", 1);
        //分账订单详情
        JSONArray splitRefundList = new JSONArray();
        JSONObject splits = new JSONObject();
        splits.put("bizUserId", "test0003");
        splits.put("amount", 1);

        splitRefundList.add(splits);

        object.put("splitRefundList", splitRefundList);
        orderRefundList.add(object);
        param.put("orderRefundList", orderRefundList);

        try {
            final OpenResponse response = client.execute("allinpay.yunst.orderService.orderSplitRefund", param);
            return response;
//            if (response.getCode().equals("10000") && "OK".equals(response.getSubCode())) {
//                return JSONObject.parseObject(response.getData());
//            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


//    /**
//     * 查询订单结果
//     * @return
//     */
//    @GetMapping(value = "/query")
//    public OpenResponse query(){
//        configClient();
//        BizParameter param = new BizParameter();
//        param.put("orderNo", "1732221663170338816");
//        param.put("bizOrderNo", "789522336512322567");
//        param.put("amount", 10);
//        param.put("buyerBizUserId", "yc0001");
//        //状态“OK”标识支付成功；“pending”表示进行中（中间状态）   “error”表示支付失败；
//        param.put("status", "OK");
//        try {
//            final OpenResponse response = client.execute("allinpay.yunst.orderService.pay", param);
//            return  response;
//        } catch (final Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 查询状态
     *
     * @return
     */
    public static JSONObject getOrderStatus(String orderId, String bizOrderNo) {
        configClient();
        BizParameter param = new BizParameter();
        param.put("orderNo", "1739468344161017856");
        param.put("bizOrderNo", "154651516178668");
        try {
            final OpenResponse response = client.execute("allinpay.yunst.orderService.getOrderStatus", param);
            if ("OK".equals(response.getSubCode())) {
                return JSONObject.parseObject(response.getData());
            }
//            code   10000         "code": "10000" , "subCode": "OK"  ,  "subMsg": "",

//            return  JSONObject.parseObject(response.getData());
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static JSONObject getOrderDetail(String orderId, String bizOrderNo) {
        configClient();
        BizParameter param = new BizParameter();
        param.put("orderNo", "1739475238539829248");
        param.put("bizOrderNo", "1703558189861df");
        try {
            final OpenResponse response = client.execute("allinpay.yunst.orderService.getOrderDetail", param);
            if ("OK".equals(response.getSubCode())) {
                return JSONObject.parseObject(response.getData());
            }
//            code   10000         "code": "10000" , "subCode": "OK"  ,  "subMsg": "",

//            return  JSONObject.parseObject(response.getData());
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 订单分账明细查询
     */
    public static JSONObject getOrderSplitRuleListDetail() {
        configClient();
        final BizParameter param = new BizParameter();
        param.put("bizOrderNo", "1703560388042df");
        try {
            final OpenResponse response = client.execute("allinpay.yunst.orderService.getOrderSplitRuleListDetail", param);
            if (response.getCode().equals("10000") && "OK".equals(response.getSubCode())) {
                return JSONObject.parseObject(response.getData());
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 查询余额
     */
    public static OpenResponse queryBalance() {
        configClient();
        final BizParameter param = new BizParameter();
        param.put("bizUserId", "test000022");
        param.put("accountSetNo", "400254");

        try {
            final OpenResponse response = client.execute("allinpay.yunst.orderService.queryBalance", param);
            return response;
//            if ("OK".equals(response.getSubCode())) {
//                System.out.println(response.getData());
//            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 个人会员注册并实名
     */

    public static OpenResponse memberRegistAndSetRealName() {
        configClient();
        final BizParameter param = new BizParameter();
        param.put("bizUserId", "test2003");
        param.put("name", "王三华");
        param.put("identityType", 1L);
        param.put("identityNo", client.encrypt("420324197711160623"));
        //param.put("identityBeginDate", "2010-12-31");
        //param.put("identityEndDate", "9999-12-31");
        //param.put("address", "");
        //param.put("professionNo", "");
        //param.put("telephone", "");

        try {
            final OpenResponse response = client.execute("allinpay.yunst.memberService.memberRegistAndSetRealName", param);
//            if ("OK".equals(response.getSubCode())) {
//                System.out.println(response.getData());
//            }
            return response;
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 个人会员实名认证
     */
    public static OpenResponse setRealName() {
        configClient();
        final BizParameter param = new BizParameter();
        param.put("bizUserId", "test000022");
        param.put("isAuth", "true");
        param.put("name", "王三华");
        param.put("identityType", 1L);
        param.put("identityNo", client.encrypt("110101200808087633"));// 敏感数据加密
        //param.put("identityBeginDate", "2010-12-31");
        //param.put("identityEndDate", "9999-12-31");
        //param.put("address", "");
        //param.put("professionNo", "");
        //param.put("telephone", "");
        try {
            final OpenResponse response = client.execute("allinpay.yunst.memberService.setRealName", param);
            return response;
//            if ("OK".equals(response.getSubCode())) {
//                System.out.println(response.getData());
//            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置企业信息
     */
    public static JSONObject setCompanyInfo(SmtCompanyInfo smtCompanyInfo) {
        configClient();
        final BizParameter param = new BizParameter();
        param.put("bizUserId", smtCompanyInfo.getBizUserId());
//         1-企业 2-个体工商户 3-事业单位
        param.put("comproperty", Long.valueOf(smtCompanyInfo.getComproperty()));
        param.put("backUrl", "http://ceshi.allinpay.com");
        final Map<String, Object> companyBasicInfo = new LinkedHashMap<>();
//        companyBasicInfo.put("companyName", "竹溪县子怡鞋店");
//        companyBasicInfo.put("companyAddress", "上海浦东新区金沪路");
        companyBasicInfo.put("companyName", smtCompanyInfo.getCompanyName());
        if (StringUtils.isNotEmpty(smtCompanyInfo.getCompanyAddress())) {
            companyBasicInfo.put("companyAddress", smtCompanyInfo.getCompanyAddress());
        }
        companyBasicInfo.put("authType", 1L);
//        if ()
        companyBasicInfo.put("uniCredit", "92420324MA4D68J28J");
        companyBasicInfo.put("businessLicense", "222222");
        companyBasicInfo.put("organizationCode", "333333");
        companyBasicInfo.put("taxRegister", "444444");
//        companyBasicInfo.put("expLicense", "2099-1-1");

//        companyBasicInfo.put("telephone", "555555");
        companyBasicInfo.put("legalName", "王三华");
        companyBasicInfo.put("identityType", 1L);
        companyBasicInfo.put("legalIds", client.encrypt("420324197711160623"));
        //companyBasicInfo.put("identityBeginDate", "2010-12-31");
        //companyBasicInfo.put("identityEndDate", "9999-12-31");
        companyBasicInfo.put("legalPhone", "666666");
        if (smtCompanyInfo.getComproperty() == 1) {
            companyBasicInfo.put("acctType", 1L);

        } else companyBasicInfo.put("acctType", Long.valueOf(smtCompanyInfo.getAcctType()));
        if (companyBasicInfo.get("acctType").equals(1)) {
            companyBasicInfo.put("bankName", "农业银行");
            companyBasicInfo.put("unionBank", "103611001012");
            companyBasicInfo.put("parentBankName", "农业银行");
            companyBasicInfo.put("bankCityNo", "777777");
        } else {
            companyBasicInfo.put("phone", "555555");
        }


        //对私必填
        //
        companyBasicInfo.put("accountNo", client.encrypt("6228480402637874215"));


//        companyBasicInfo.put("province", "");
//        companyBasicInfo.put("city", "");

        param.put("companyBasicInfo", companyBasicInfo);

        try {
            final OpenResponse response = client.execute("allinpay.yunst.memberService.setCompanyInfo", param);
            if (response.getCode().equals("10000") && "OK".equals(response.getSubCode())) {
                return JSONObject.parseObject(response.getData());
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 提现申请
     */

    public static OpenResponse withdrawApply() {
        configClient();
        //电子账户代付
        HashMap<String, Object> WITHDRAW_TEA = new HashMap<>();
        WITHDRAW_TEA.put("amount", "1");
        //WITHDRAW_TEA.put("unionBank", "308290003123");
        //WITHDRAW_TEA.put("bankName", "招商银行股份有限公司上海大连路支行");
        //WITHDRAW_TEA.put("province", "");//
        //WITHDRAW_TEA.put("city", "");

        //通联通代付
        HashMap<String, Object> WITHDRAW_TLT = new HashMap<>();
        WITHDRAW_TLT.put("payTypeName", "withdraw_tlt");//必传payTypeName
        //WITHDRAW_TLT.put("unionBank", "123456789123");
        //WITHDRAW_TLT.put("bankName", "");
        //WITHDRAW_TLT.put("province", "");
        //WITHDRAW_TLT.put("businessCode", "09800");

        // 组装支付方式
        HashMap<String, Object> payMethod = new HashMap<>();
        payMethod.put("WITHDRAW_TLT", WITHDRAW_TLT);
        //payMethod.put("WITHDRAW_TEA", WITHDRAW_TEA);

        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, 15);
        final Date date = calendar.getTime();
        final String orderExpireDatetime = sdf.format(date);
        final BizParameter param = new BizParameter();
        param.put("bizUserId", "test000022");
        param.put("bizOrderNo", System.currentTimeMillis() + "tx");
        param.put("accountSetNo", "400254");
        param.put("amount", 1L);
        param.put("fee", 0L);
        param.put("validateType", 1L);
        param.put("backUrl", "http://ceshi.allinpay.com");
        param.put("orderExpireDatetime", orderExpireDatetime);
        param.put("payMethod", payMethod);
        param.put("bankCardNo", client.encrypt("6228480402637874321"));
        param.put("bankCardPro", 0L);
        param.put("withdrawType", "D0");
        param.put("industryCode", "1010");
        param.put("industryName", "保险代理");
        param.put("source", 2L);
        param.put("summary", "withdraw");
        param.put("extendInfo", "this is extendInfo");

        try {
            final OpenResponse response = client.execute("allinpay.yunst.orderService.withdrawApply", param);
            return response;
//            if ("OK".equals(response.getSubCode())) {
//                System.out.println(response.getData());
//            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 申请绑定银行卡
     */
    public static OpenResponse applyBindBankCard() {
        configClient();
        final BizParameter param = new BizParameter();
        param.put("bizUserId", "test000022");
        param.put("cardNo", client.encrypt("6228480402637874321"));
        param.put("phone", "13712312311");
        param.put("name", "王三华");
        param.put("cardCheck", 6L);
        param.put("identityType", 1L);
        param.put("identityNo", client.encrypt("110101200808087633"));
        //param.put("validate", client.encrypt("205012"));
        //param.put("cvv2", client.encrypt("321"));
        //param.put("unionBank", "");
        try {
            final OpenResponse response = client.execute("allinpay.yunst.memberService.applyBindBankCard", param);
//            if ("OK".equals(response.getSubCode())) {
//                System.out.println(response.getData());
//            }
            return response;
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 确认绑定银行卡
     */
    public static OpenResponse bindBankCard() {
        configClient();
        final BizParameter param = new BizParameter();
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        param.put("bizUserId", "test000022");
        param.put("tranceNum", "1733455339031896064");// 申请绑卡时返回的tranceNum
        //param.put("transDate", sdf.format(new Date()));
        param.put("phone", "13712312311");
        //param.put("validate", client.encrypt("1223"));
        //param.put("cvv2", client.encrypt("123"));
        param.put("verificationCode", "111111");
        try {
            final OpenResponse response = client.execute("allinpay.yunst.memberService.bindBankCard", param);
            return response;
//            if ("OK".equals(response.getSubCode())) {
//                System.out.println(response.getData());
//            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 企业会员信息修改
     */
    public void updateCompanyInfo() {
        configClient();
        final BizParameter param = new BizParameter();
        param.put("bizUserId", "test1001");
        param.put("reqsn", System.currentTimeMillis() + "ls");
        param.put("companyName", "竹溪县子怡鞋店");
        param.put("companyAddress", "上海浦东新区金沪路");
        param.put("telephone", "555555");
        param.put("legalName", "王三华");
        param.put("identityType", 1L);
        param.put("legalIds", client.encrypt("420324197711160623"));
        //param.put("identityBeginDate", "2010-12-31");
        //param.put("identityEndDate", "9999-12-31");
        param.put("legalPhone", "777777");
        //param.put("backUrl","");

        try {
            final OpenResponse response = client.execute("allinpay.yunst.memberService.updateCompanyInfo", param);
            if ("OK".equals(response.getSubCode())) {
                System.out.println(response.getData());
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询(个人、企业)会员信息
     */
    public static OpenResponse getMemberInfo() {
        configClient();
        final BizParameter param = new BizParameter();
        param.put("bizUserId", "test000023");
        //param.put("acctOrgType", 0L);
        try {
            final OpenResponse response = client.execute("allinpay.yunst.memberService.getMemberInfo", param);
//            if ("OK".equals(response.getSubCode())) {
//                System.out.println(response.getData());
//                final JSONObject data = JSON.parseObject(response.getData());
//                if(data.getLong("memberType") == 2L)
//                {
//                    System.out.println(client.decrypt(data.getJSONObject("memberInfo").getString("accountNo")));// test
//                }
//            }
            return response;
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 企业信息审核结果通知
     */
    public static OpenResponse verifyResult() {
        configClient();
        final BizParameter param = new BizParameter();
        param.put("bizUserId", "test000023");
        param.put("result", "2");
        param.put("checkTime", "2023-12-18");
        try {
            final OpenResponse response = client.execute("allinpay.yunst.memberService.verifyResult", param);
            return response;
//            if ("OK".equals(response.getSubCode())) {
//                System.out.println(response.getData());
//            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 账户提现协议签约
     */
    public static String signAcctProtocol() {
        configClient();
        final BizParameter param = new BizParameter();
        param.put("bizUserId", "test000022");
        param.put("signAcctName", "王三华");
        //param.put("jumpPageType", 1L);
        //param.put("jumpUrl", "");
        param.put("backUrl", client.encrypt("http://ceshi.allinpay.com"));
        //param.put("noContractUrl", "");
        param.put("source", 1L);

        try {
            final String url = client.concatUrlParams("allinpay.yunst.memberService.signAcctProtocol", param);
            return url;
            //browser(url);// 打开浏览器
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 影印件采集
     */
    public static JSONObject idcardCollect(String imageUrl) {
        configClient();
        final BizParameter param = new BizParameter();
        param.put("bizUserId", "test000023");
        //param.put("ocrComparisonResultBackUrl", "");
        param.put("picType", 1L);
//        param.put("picture", BizUtils.JPGToBase64("D:\\微信图片_20231209113932.png"));
        param.put("picture", Allinpay.ImageBase64(imageUrl));
        try {
            final OpenResponse response = client.execute("allinpay.yunst.memberService.idcardCollect", param);
            if (response.getCode().equals("10000") && "OK".equals(response.getSubCode())) {
                return JSONObject.parseObject(response.getData());
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 影印件采集（文件上传模式）
     * 需配置utils包下FileUtils中的应用对应参数
     */
    public void idcardCollectByFileUpload() throws InterruptedException {
        final BizParameter param = new BizParameter();
        param.put("bizUserId", "test0003");
        param.put("reqSerialNo", System.currentTimeMillis() + "11");
        //param.put("ocrComparisonResultBackUrl", "");
        String legalPicFaceToken = FileUtils.uploadFile("C:\\test1.jpeg");
        if (StringUtils.isNotEmpty(legalPicFaceToken)) {
            param.put("legalPicFaceToken", legalPicFaceToken);
        }
        TimeUnit.SECONDS.sleep(5);
        String legalPicEmblemToken = FileUtils.uploadFile("C:\\test2.jpeg");
        if (StringUtils.isNotEmpty(legalPicEmblemToken)) {
            param.put("legalPicEmblemToken", legalPicEmblemToken);
        }
        //param.put("picType", "");
        //param.put("token", "");
        try {
            final OpenResponse response = client.execute("allinpay.yunst.memberService.idcardCollectByFileUpload", param);
            if ("OK".equals(response.getSubCode())) {
                System.out.println(response.getData());
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }


    public static String ImageBase64(String imgUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try {
            System.out.println(imgUrl);
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();

            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = is.read(buffer)) != -1) {
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return Base64Utils.encode(outStream.toByteArray());
//            return new BASE64Encoder().encode(outStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpUrl != null) {
                httpUrl.disconnect();
            }
        }
        return null;
    }


    /**
     * 把Base图片下载到本地
     *
     * @param imageUrl
     * @param base64
     * @param path
     * @return
     */
    public static Boolean base64ToFile(String imageUrl, String base64, String path) {
        byte[] buffer;
        try {
            base64 = Allinpay.ImageBase64(imageUrl);
            buffer = org.springframework.util.Base64Utils.decodeFromString(base64);
            FileOutputStream out = new FileOutputStream(path);
            out.write(buffer);
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 单笔托管代付（标准版）
     */
    public static OpenResponse signalAgentPay() {
        configClient();
        final BizParameter param = new BizParameter();
        // 源托管代收订单付款信息
        final JSONArray collectPayList = new JSONArray();
        final HashMap<String, Object> collect1 = new HashMap<>();
        collect1.put("bizOrderNo", "15465151617866778");
        collect1.put("amount", 10L);
        collect1.put("orderNo", "1739483655836868608");
        collectPayList.add(new JSONObject(collect1));
        param.put("bizUserId", "test000022");
        param.put("accountSetNo", "400254");
        param.put("bizOrderNo", System.currentTimeMillis() + "df");
        param.put("collectPayList", collectPayList);
        param.put("tradeCode", "4001");
        param.put("amount", 10L);
        param.put("fee", 0L);
        param.put("backUrl", "http://ceshi.allinpay.com");
        param.put("summary", "consume");
        param.put("extendInfo", "this is extendInfo");


        final JSONArray splitRule = new JSONArray();

        JSONObject splitRule1 = new JSONObject();
        splitRule1.put("bizUserId", "test0003");
        //splitRule1.put("accountSetNo", "200001");
        splitRule1.put("amount", 2l);
        splitRule1.put("fee", 0L);
        splitRule1.put("remark", " 消费一级分账");
        splitRule.add(splitRule1);

        param.put("splitRuleList", splitRule);
        try {
            final OpenResponse response = client.execute("allinpay.yunst.orderService.signalAgentPay", param);
//            if ("OK".equals(response.getSubCode())) {
////                System.out.println(response.getData());
//
//            }
            return response;
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 消费申请接口    （实时分账）
     *
     * @param payDto
     * @return
     */
    public static JSONObject consumeApply(PayDto payDto, String orderId) {
        configClient();
        BizParameter param = new BizParameter();
        param.put("payerId", "yc0001");
        param.put("recieverId", "test000022");
        param.put("bizOrderNo", orderId);
//        param.put("phone", "18812345678");
        //转分
        BigDecimal multiply = payDto.getActualPrice().multiply(BigDecimal.valueOf(100));
        param.put("amount", multiply.longValue());
        param.put("fee", 2l);
        param.put("backUrl", "http://ceshi.allinpay.com");
        JSONObject payMethod = new JSONObject();
        payMethod.put("amount", multiply.longValue());
        payMethod.put("authcode", payDto.getAuthCode());
        payMethod.put("limitPay", "");
//        payMethod.put("wxAppId", "wx23ab834e27fd68ea");
//        payMethod.put("wxMchtId", "1570120791");
//        payMethod.put("amount", "100");
//        payMethod.put("limitPay", "");
//        payMethod.put("cusip", "192.168.1.15");

        JSONObject object = new JSONObject();
//        object.put("WECHATPAY_SCAN_OPEN", payMethod);
        object.put("CODEPAY_VSP", payMethod);
        param.put("payMethod", object);
        param.put("industryCode", "2413");
        param.put("industryName", "电子产品");
        param.put("source", 2L);
//        //分账规则
//        final JSONArray splitRule = new JSONArray();
//
//        JSONObject splitRule1 = new JSONObject();
//        splitRule1.put("bizUserId", "test0003");
//        //splitRule1.put("accountSetNo", "200001");
//        splitRule1.put("amount", 2l);
//        splitRule1.put("fee", 0L);
//        splitRule1.put("remark", " 消费一级分账");
//        splitRule.add(splitRule1);
//
//        param.put("splitRule", splitRule);

        try {
            log.info("请求参数：" + param);
            OpenResponse response = client.execute("allinpay.yunst.orderService.consumeApply", param);
            log.info("测试结果：" + response);
            if (response.getCode().equals("10000") && "OK".equals(response.getSubCode())) {
                return JSONObject.parseObject(response.getData());
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 托管代收申请（标准版）
     */
    public static JSONObject agentCollectApply(PayDto payDto, String orderId) {
        configClient();
//        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        final Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.HOUR, 15);
//        final Date date = calendar.getTime();
//        final String orderExpireDatetime = sdf.format(date);
        final BizParameter param = new BizParameter();
        BigDecimal multiply = payDto.getActualPrice().multiply(BigDecimal.valueOf(100));
        // 支付方式
        JSONObject payMethod = new JSONObject();
        payMethod.put("amount", multiply.longValue());
        payMethod.put("authcode", payDto.getAuthCode());
        payMethod.put("limitPay", "");

        JSONObject object = new JSONObject();
//        object.put("WECHATPAY_SCAN_OPEN", payMethod);
        object.put("CODEPAY_VSP", payMethod);


        // 收款列表
        final JSONArray receiverList = new JSONArray();
        final HashMap<String, Object> receiver1 = new HashMap<>();
        receiver1.put("bizUserId", "test000022");
        receiver1.put("amount", multiply.longValue());
        receiverList.add(new JSONObject(receiver1));


        param.put("payerId", "yc0001");
        param.put("bizOrderNo", orderId);
        param.put("recieverList", receiverList);
        param.put("tradeCode", "3001");
        param.put("amount", multiply.longValue());
        param.put("fee", 0L);
        param.put("validateType", 0L); // 1 短信验证
        param.put("frontUrl", "http://ceshi.allinpay.com");
        param.put("backUrl", "http://ceshi.allinpay.com");
//        param.put("orderExpireDatetime", orderExpireDatetime);
        param.put("payMethod", object);
        //param.put("goodsName", "虚拟商品");
        //param.put("goodsDesc", "computer made in china");
        param.put("industryCode", "2413");
        param.put("industryName", "电子产品");
        param.put("source", 2L);
//        param.put("summary", "consume");
        param.put("extendInfo", "this is extendInfo");
        try {
            final OpenResponse response = client.execute("allinpay.yunst.orderService.agentCollectApply", param);
            if (response.getCode().equals("10000") && "OK".equals(response.getSubCode())) {
                return JSONObject.parseObject(response.getData());
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
